/**
 * 
 */
package manager;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;

import utils.DomainDAORemote;
import utils.TechresourceDAORemote;
import dtos.DomainDTO;
import dtos.TechresourceDTO;
import dtos.UserDTO;

/**
 * @author Istvan Szabo
 * 
 */

@ManagedBean(name = "techresourceBean")
@SessionScoped
public class TechresourceBean implements Serializable {

	private static final long serialVersionUID = 1085527583601416326L;

	final Logger logger = Logger.getLogger(ResourceBean.class.getName());

	ResourceBundle bundle = ResourceBundle.getBundle(
			"languageSettings.language", FacesContext.getCurrentInstance()
					.getViewRoot().getLocale());

	/**
	 * Bean for managing new techresource fields
	 */
	private TechresourceDTO newTechresourceDTO;
	/**
	 * Bean managing edit techresource fields
	 */
	private TechresourceDTO editTechresourceDTO;

	@EJB
	private TechresourceDAORemote techresourceDAO;

	@EJB
	private DomainDAORemote domainDAO;

	/**
	 * List of techresources displayed on the page
	 */
	private List<TechresourceDTO> techresourceDTOs;

	/**
	 * Search key for techresources
	 */
	private String searchKey = "";
	/**
	 * Toggle new fields
	 */
	private boolean showNew = false;
	/**
	 * Feedback shown after operations
	 */
	private String feedback = " ";

	private boolean admin = false;

	public TechresourceBean() {

	}

	/**
	 * Initializes DTOs
	 */
	@PostConstruct
	public void init() {
		newTechresourceDTO = new TechresourceDTO();
		resetNewDTO();

		editTechresourceDTO = new TechresourceDTO();
		editTechresourceDTO.setName("");
		editTechresourceDTO.setId(0);
		editTechresourceDTO.setIp("");
		editTechresourceDTO.setIdnumber(0);
		editTechresourceDTO.setStatus("");
		editTechresourceDTO.setIdDomain(((UserDTO) FacesContext
				.getCurrentInstance().getExternalContext().getSessionMap()
				.get("loggedUser")).getIdDomain());
		techresourceDTOs = techresourceDAO
				.getTechResourcesDTOByDomainId(editTechresourceDTO
						.getIdDomain());
		admin = ((UserDTO) FacesContext.getCurrentInstance()
				.getExternalContext().getSessionMap().get("loggedUser"))
				.getIdUsertype() == 1;
	}

	private void resetNewDTO() {
		newTechresourceDTO.setName("");
		newTechresourceDTO.setId(0);
		newTechresourceDTO.setIp("xxx.xxx.xxx.xxx");
		newTechresourceDTO.setIdnumber(0);
		newTechresourceDTO.setStatus("Working");
		newTechresourceDTO.setIdDomain(((UserDTO) FacesContext
				.getCurrentInstance().getExternalContext().getSessionMap()
				.get("loggedUser")).getIdDomain());
	}

	private void setEditDTO(TechresourceDTO t) {
		editTechresourceDTO.setId(t.getId());
		editTechresourceDTO.setIp(t.getIp());
		editTechresourceDTO.setName(t.getName());
		editTechresourceDTO.setIdnumber(t.getIdnumber());
		editTechresourceDTO.setStatus(t.getStatus());
		editTechresourceDTO.setIdDomain(t.getIdDomain());
	}

	private void applySearchKey() {
		logger.log(Level.INFO, "filter key: " + searchKey + " returning: "
				+ techresourceDTOs);
		if (editTechresourceDTO.getId() != 0) {
			techresourceDTOs.clear();
			techresourceDTOs.add(editTechresourceDTO);
		} else {
			techresourceDTOs = techresourceDAO
					.getTechresourcesByName(searchKey);
			if (!admin) {
				List<TechresourceDTO> temp = new ArrayList<>(techresourceDTOs);
				int domainId = ((UserDTO) FacesContext.getCurrentInstance()
						.getExternalContext().getSessionMap().get("loggedUser"))
						.getIdDomain();
				for (TechresourceDTO t : temp) {
					if (t.getIdDomain() != domainId)
						techresourceDTOs.remove(t);
				}
			}
		}
	}

	public void applyFilter(AjaxBehaviorEvent e) {
		applySearchKey();
	}

	/**
	 * Toggles new techresource fields
	 * 
	 * @param e
	 */
	public void showNewFields(AjaxBehaviorEvent e) {
		logger.log(Level.INFO, "showing new fields");
		showNew = !showNew;
	}

	public void addNewTechresource(AjaxBehaviorEvent e) {
		logger.log(Level.INFO, "adding new techresource");
		List<TechresourceDTO> tdtos = techresourceDAO.getAllTechresources();
		for (TechresourceDTO r : tdtos) {
			if (newTechresourceDTO.getName().trim()
					.equalsIgnoreCase(r.getName().trim())) {
				logger.log(Level.INFO, "found name");
				feedback = bundle
						.getString("Beans_manager_techresourceBean_feedbackdupl");
				return;
			}
		}
		// take from logged in user on session
		newTechresourceDTO.setIdDomain(((UserDTO) FacesContext
				.getCurrentInstance().getExternalContext().getSessionMap()
				.get("loggedUser")).getIdDomain());
		techresourceDAO.insertTechresource(newTechresourceDTO);
		resetNewDTO();
		searchKey = "";
		feedback = bundle
				.getString("Beans_manager_techresourceBean_feedbackadd");
		applySearchKey();
	}

	public void performDelete(ActionEvent event) {
		// perform deletion
		TechresourceDTO dt = (TechresourceDTO) event.getComponent()
				.getAttributes().get("deleteTResource");
		if (dt.getTechtickets().size() == 0) {
			techresourceDAO.deleteTechresource(dt);
			logger.log(Level.INFO, "performing delete");
			// show confirmation message
			this.feedback = bundle
					.getString("Beans_manager_techresourceBean_feedbackdelete");
			applySearchKey();
		} else
			feedback = bundle
					.getString("Beans_manager_techresourceBean_feedbackinuse");
	}

	/**
	 * Marks the row as editable, displays that row only
	 * 
	 * @param event
	 */
	public void markForEdit(ActionEvent event) {
		editTechresourceDTO = new TechresourceDTO();
		TechresourceDTO t = (TechresourceDTO) event.getComponent()
				.getAttributes().get("editTResource");
		setEditDTO(t);
		// editTechresourceDTO.setId();
		logger.log(Level.INFO, "id to be edited:" + editTechresourceDTO.getId());
		showNew = false;
		applySearchKey();
	}

	public void saveEdit(ActionEvent event) {
		// update resource
		logger.log(Level.INFO,
				"saving edited:" + editTechresourceDTO.getId() + " "
						+ editTechresourceDTO.getName() + " "
						+ editTechresourceDTO.getIp() + " "
						+ editTechresourceDTO.getIdnumber() + " "
						+ editTechresourceDTO.getStatus() + " "
						+ editTechresourceDTO.getIdDomain());

		List<TechresourceDTO> tdtos = techresourceDAO.getAllTechresources();
		for (TechresourceDTO r : tdtos) {
			if (editTechresourceDTO.getId() != r.getId()
					&& editTechresourceDTO.getName().trim()
							.equalsIgnoreCase(r.getName().trim())) {
				logger.log(Level.INFO, "found name");
				feedback = bundle
						.getString("Beans_manager_techresourceBean_feedbackdupl");
				return;
			}
		}
		// get it from session
		editTechresourceDTO.setIdDomain(((UserDTO) FacesContext
				.getCurrentInstance().getExternalContext().getSessionMap()
				.get("loggedUser")).getIdDomain());
		techresourceDAO.updateTechresource(editTechresourceDTO);
		this.feedback = bundle
				.getString("Beans_manager_techresourceBean_feedbacksaved");
		editTechresourceDTO.setId(0);
		applySearchKey();
	}

	public String cancelEdit() {
		editTechresourceDTO.setId(0);
		logger.log(Level.INFO, "caneled editing");
		applySearchKey();
		return "resourceCRUD.xhtml";
	}

	public void resetEdit(AjaxBehaviorEvent e) {
		cancelEdit();
	}

	public DomainDTO domainOf(TechresourceDTO tDTO) {
		return domainDAO.getDomain(tDTO.getIdDomain());
	}

	public List<TechresourceDTO> getTechresourceDTOs() {
		return techresourceDTOs;
	}

	public void setTechresourceDTOs(List<TechresourceDTO> techresourceDTOs) {
		this.techresourceDTOs = techresourceDTOs;
	}

	public String getSearchKey() {
		return searchKey;
	}

	public void setSearchKey(String searchKey) {
		this.searchKey = searchKey;
	}

	public boolean isShowNew() {
		return showNew;
	}

	public void setShowNew(boolean showNew) {
		this.showNew = showNew;
	}

	public TechresourceDTO getNewTechresourceDTO() {
		return newTechresourceDTO;
	}

	public void setNewTechresourceDTO(TechresourceDTO newTechresourceDTO) {
		this.newTechresourceDTO = newTechresourceDTO;
	}

	public String getFeedback() {
		return feedback;
	}

	public void setFeedback(String feedback) {
		this.feedback = feedback;
	}

	public TechresourceDTO getEditTechresourceDTO() {
		return editTechresourceDTO;
	}

	public void setEditTechresourceDTO(TechresourceDTO editTechresourceDTO) {
		this.editTechresourceDTO = editTechresourceDTO;
	}

	public boolean isAdmin() {
		return admin;
	}

	public void setAdmin(boolean admin) {
		this.admin = admin;
	}

}
